// @Author EthanScriptOn
// @Desc
package component

import (
	"gitee.com/fatzeng/srf_switch/config"
	"gitee.com/fatzeng/srf_switch/core"
	"gitee.com/fatzeng/srf_switch/core/switch_subject"
	"gitee.com/fatzeng/srf_switch/core/switch_subject/statistics"
	"gitee.com/fatzeng/srf_switch_basic_components/switch_log"
)

type SrfComponent struct {
	ruleFilter   switch_subject.Filter
	outputFields []string
}

func GenerateSrfComponent(ruleFilter switch_subject.Filter, outputFields []string) *SrfComponent {
	return &SrfComponent{
		ruleFilter:   ruleFilter,
		outputFields: outputFields,
	}
}

func (s *SrfComponent) IsSwitchOnRule(ctx *core.SrfSwitchContext, srfRule *switch_subject.SrfRule) bool {
	if srfRule == nil {
		return false
	}
	statisticSwitchName := config.SrfSwitchGlobalConfig.SrfCoreOptionsConfig.SrfStatisticSwitchName
	if statisticSwitchName == "" {
		statisticSwitchName = switch_subject.IS_OPEN_SWITCH_STATISTIC
	}
	if s.IsSwitchOn(ctx, statisticSwitchName) {
		outPutFields := s.outputFields
		opFields := ctx.Value(switch_subject.OUT_PUT_FIELDS)
		if outPutAsSlice, ok := opFields.([]string); ok {
			outPutFields = append(outPutFields, outPutAsSlice...)
		}
		statistic := statistics.GenerateSwitchStatistic(outPutFields)
		ctx.Set(switch_subject.STATISTIC, &statistic)
	}
	filterRes := s.ruleFilter.Filter(ctx, srfRule)
	return filterRes
}

func (s *SrfComponent) IsSwitchOn(ctx *core.SrfSwitchContext, switchName string) bool {
	if switchName == "" {
		return false
	}
	rule, canFound := GetRule(switchName)
	if !canFound {
		switch_log.Logger().Warn("unable to find switch_subject named :", switchName)
	}
	return s.IsSwitchOnRule(ctx, rule)
}
